package com.atu.atugra.controller;
 
 
 
import com.atu.atugra.entity.Products;
import com.atu.atugra.service.ProductsService;
import com.atu.atugra.tools.CommonResult;
import com.atu.atugra.vo.ProListVO;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * (Products)表控制层
 *
 * @author makejava
 * @since 2025-02-07 12:04:16
 */
@RestController
@RequestMapping("products")
public class ProductsController{
    @Autowired
    private ProductsService productsService;
    //获取列表
    @GetMapping("list")
    public CommonResult list(@RequestParam Integer page, @RequestParam Integer size){
        return productsService.getPage(page,size);
    }
    @GetMapping("Mlist")
    public CommonResult Mlist(@RequestParam Integer page, @RequestParam Integer size, @RequestParam String keyword){
        return productsService.getMPage(page,size,keyword);
    }
    //根据id获取
    @GetMapping("getById/{id}")
    public CommonResult getById(@PathVariable Integer id){
        return CommonResult.okResult(productsService.getById(id));
    }
    //新增
    @PostMapping("add")
    public CommonResult add(@RequestBody Products products){
        return productsService.insert(products);
    }
    //修改
    @PostMapping("update")
    public CommonResult update(@RequestBody Products products){
        return productsService.updatePro(products);
    }
    //删除
    @DeleteMapping("delete")
    public CommonResult delete(@RequestParam Integer id){
       return productsService.deletePro(id);
    }
    /**
     * 搜索商品接口
     * @param keyword 搜索关键词
     * @param categoryId 分类ID
     * @param page 页码
     * @param pageSize 每页大小
     * @return CommonResult<List<Product>>
     */
    @GetMapping("/search")
    public CommonResult searchProducts(
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) Long categoryId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize) {

        try {
            List<ProListVO> productList = productsService.searchProducts(keyword, categoryId, page, pageSize);
            return CommonResult.okResult(productList);
        } catch (Exception e) {
            return CommonResult.failed("查询商品失败: " + e.getMessage());
        }
    }
}
